<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { storeToRefs } from 'pinia'
import { Attach20Regular } from '@vicons/fluent'
import { Icon } from '@vicons/utils'
import { useModelStore } from '@/stores/model'
import { message } from 'ant-design-vue'

const { t, locale } = useI18n()

// 模型存储
const modelStore = useModelStore()
const { readActiveModelInfo } = storeToRefs(modelStore)

// 定义事件
const emits = defineEmits(['change'])

// 状态参数
const state = reactive({
  allowUpload: false,
  tips: '',
  accept: '',
})

// 组件
const fileRef = ref()

// 选择文件
const onChooseFile = async (e: any) => {
  const file = e.target.files[0] ?? null
  if (file) {
    try {
      await modelStore.checkCurrentModelAttach(file)
      emits('change', file)
    } catch (e) {
      message.error(e.message)
    }
  }
  fileRef.value.value = ''
}

// 监听模型切换，重新渲染上传提示
// 这里同时监听了语言变更，保证切换语言后文本也会变更
watch(
  [readActiveModelInfo, locale],
  async () => {
    const tips = await modelStore.getCurrentModelAttachUploadTips()
    state.allowUpload = tips.allowUpload && !!readActiveModelInfo.value
    state.tips = tips.tips
    state.accept = tips.accept
  },
  {
    immediate: true,
  },
)
</script>

<template>
  <a-tooltip placement="top">
    <template #title>
      <template v-if="!readActiveModelInfo">{{ t('model.selectModelTip') }}</template>
      <template v-else>
        <div>{{ t('system.attachmentUpload.title') }}</div>
        <div class="limit">
          {{ state.tips }}
        </div>
      </template>
    </template>
    <n-button
      type="default"
      secondary
      :disabled="!state.allowUpload"
      @click="() => fileRef.click()"
    >
      <template #icon>
        <Icon><Attach20Regular /></Icon>
      </template>
    </n-button>
  </a-tooltip>
  <input
    type="file"
    ref="fileRef"
    @change="onChooseFile"
    style="display: none"
    :accept="state.accept"
  />
</template>

<style lang="scss" scoped>
.limit {
  font-size: 13px;
  margin-top: 5px;
  color: #bbb;
}
</style>
